package cn.jsc.basic.controller;

import cn.jsc.basic.util.AjaxResult;
import cn.jsc.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 *  上传
 *  下载 - 不用
 *  删除
 *  查询： - http://47.95.117.210:8888/
 *  修改：= 删除 + 上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    /**
     * 文件上传接口：file必须和elementUi提供的上传组件保持一致【neme="file" post】
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true, value = "file") MultipartFile file){
        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();  //   xxx/404.jpg
            int index = originalFilename.lastIndexOf(".");
            String extName = originalFilename.substring(index + 1); // jpg
            String fileName = FastDfsUtil.upload(file.getBytes(), extName);
            System.out.println("上传成功...");
            return AjaxResult.me().setResultObj(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("上传失败...");
        }
    }

    //请求方式：delete  请求参数：fastDfs?path=/group1/M00/02/1B/rBE3kWHC4bKAbYgKAAgFDuhQH8Q583.gif
    @DeleteMapping
    public AjaxResult del(@RequestParam(required = true,value = "path") String path){

        try {
            //   /group1/M00/02/1B/rBE3kWHC4bKAbYgKAAgFDuhQH8Q583.gif
            String pathTmp = path.substring(1); // group1/M00/02/1B/rBE3kWHC4bKAbYgKAAgFDuhQH8Q583.gif
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //   group1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// M00/02/1B/rBE3kWHC4bKAbYgKAAgFDuhQH8Q583.gif
            FastDfsUtil.delete(groupName,remotePath);
            System.out.println("删除成功");
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败...");
        }
    }
}
